package com.lishe.lishe.lishe.module.myorder.activity;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.lishe.lishe.R;
import com.lishe.lishe.Imageloader.ImageLoaderUtils;
import com.lishe.lishe.lishe.base.BaseActivity;
import com.lishe.lishe.lishe.bean.UserAddressObject;
import com.lishe.lishe.lishe.common.CommonUtils;
import com.lishe.lishe.lishe.common.Globals;
import com.lishe.lishe.lishe.module.mall.activity.MallGoodsActivity;
import com.lishe.lishe.lishe.module.myorder.bean.BusinessObject;
import com.lishe.lishe.lishe.module.myorder.bean.GoodObject;
import com.lishe.lishe.lishe.module.myorder.bean.OrderObject;
import com.lishe.lishe.lishe.module.myorder.http.HttpMyOrder;
import com.lishe.lishe.lishe.module.pay.activity.PayActivity;
import com.lishe.lishe.lishe.utils.LoadingUtils;
import com.lishe.lishe.lishe.widget.ConfirmDialog;
import com.loopj.android.http.AsyncHttpResponseHandler;

import org.json.JSONException;
import org.json.JSONObject;

import cz.msebera.android.httpclient.Header;

/**
 * Created by lwa on 2017/8/15.
 */

public class OrderDetailsActivity extends BaseActivity implements View.OnClickListener {

    private LinearLayout contentLayout;
    private Button btnBack;
    private Button btnPay;
    private Button btnCancle;
    private TextView texTtitle;
    private TextView texOrderNo;
    private TextView texOrderStatus;
    private TextView texUserName;
    private TextView texUserPhone;
    private TextView texUserAddress;
    private TextView texTotalPay;
    private ImageView QQ;
    private ImageView phone;

    private UserAddressObject userAddress;
    private OrderObject order;
    private ImageLoaderUtils imageLoaderUtils;
    private String[] orderBtnType;
    private String windowMsg;
    private ConfirmDialog.Builder cancleOrderDialog;
    private String token;

    public static void jump(Activity activity, OrderObject order) {
        Intent intent = new Intent(activity, OrderDetailsActivity.class);
        intent.putExtra("order", order);
        activity.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        token = Globals.getToken();
        orderBtnType = context.getResources().getStringArray(R.array.order_btn_type);
        setContentView(R.layout.activity_order_details);
        imageLoaderUtils = new ImageLoaderUtils();
        order = (OrderObject) getIntent().getSerializableExtra("order");
        initView();
        new GetOrderAddress().execute();
    }

    private void initView() {
        contentLayout = findViewById(R.id.content_layout);
        texTtitle = findViewById(R.id.title_text_title);
        texOrderNo = findViewById(R.id.order_no);
        texOrderStatus = findViewById(R.id.order_status);
        texUserName = findViewById(R.id.user_name);
        texUserPhone = findViewById(R.id.user_phone);
        texUserAddress = findViewById(R.id.user_address);
        texTotalPay = findViewById(R.id.total_pay);
        QQ = findViewById(R.id.order_qq_img);
        phone = findViewById(R.id.order_phone_img);
        btnPay = findViewById(R.id.pay_button);
        btnBack = findViewById(R.id.title_left_button);
        btnCancle = findViewById(R.id.cancle_button);
        texTtitle.setText(getString(R.string.order_detail));
        texTotalPay.setText((int) (order.getMoney() * 100) + "");
        texOrderNo.setText(order.getTrade_paybillData().get(0).getPayment_id());
        btnBack.setVisibility(View.VISIBLE);
        initData();
        setListener();
    }

    private void initData() {
        if (order != null) {
            contentLayout.removeAllViews();
            String orderStatus = order.getStatusToString();
            switch (orderStatus) {
                case "待付款":
                    btnCancle.setVisibility(View.VISIBLE);
                    btnPay.setVisibility(View.VISIBLE);
                    btnCancle.setText(orderBtnType[0]);
                    btnPay.setText(orderBtnType[4]);
                    windowMsg = context.getString(R.string.iscancle_order);

                    if (order.getIs_overdue().equals("0")) {//订单已失效
                        btnCancle.setVisibility(View.GONE);
                        btnPay.setVisibility(View.GONE);
                    }
                    break;
                case "已取消":
                case "已完成":
                case "交易成功":
                    btnCancle.setVisibility(View.GONE);
                    btnPay.setVisibility(View.GONE);
                    break;
                case "待发货":
                case "买家已付款":
                    btnCancle.setVisibility(View.VISIBLE);
                    btnPay.setVisibility(View.GONE);
                    btnCancle.setText(orderBtnType[1]);
                    break;
                case "待收货"://已付款
                case "卖家已发货":

                    btnCancle.setVisibility(View.GONE);
                    btnCancle.setVisibility(View.VISIBLE);
                    btnCancle.setText(orderBtnType[2]);
                    btnPay.setVisibility(View.VISIBLE);
                    btnPay.setText(orderBtnType[3]);
                    windowMsg = context.getString(R.string.isreceive_order);
                    break;
                case "退换货":
                    btnCancle.setVisibility(View.GONE);
                    btnPay.setVisibility(View.GONE);
                    break;

            }

            for (int i = 0; i < order.getTrade_paybillData().size(); i++) {//商铺
                BusinessObject business = order.getTrade_paybillData().get(i);
                texOrderStatus.setText(order.getStatusToString());
                if (order.getStatusToString().equals("待付款") && order.getIs_overdue().equals("0")) {
                    texOrderStatus.setText("订单已失效");
                }
                View businessLayout = getLayoutInflater().inflate(R.layout.item_order_adapter_business, null);
                TextView businessName = businessLayout.findViewById(R.id.business_name);
                TextView businessStatus = businessLayout.findViewById(R.id.business_type);
                TextView busenissTotalMoney = businessLayout.findViewById(R.id.business_total_money);
                LinearLayout businessGoodsLayout = businessLayout.findViewById(R.id.goods_layout);
                businessGoodsLayout.removeAllViews();
                businessName.setText(business.getTradeData().getShopName());
                businessStatus.setText(business.getTradeData().getStatusToString());
                if (order.getStatusToString().equals("待付款") && order.getIs_overdue().equals("0")) {
                    businessStatus.setText("订单已失效");
                }
                if (business.getTradeData().getPost_fee() != 0) {
                    busenissTotalMoney.setText(String.format(context.getString(R.string.business_total_money_postfee), (int) (business.getPayment() * 100) + "", (int) ((float) business.getTradeData().getPost_fee()) + ""));
                } else {
                    busenissTotalMoney.setText(String.format(getString(R.string.business_total_money), (int) (business.getPayment() * 100) + ""));
                }
                contentLayout.addView(businessLayout);
                for (int j = 0; j < business.getTradeData().getOrderList().size(); j++) {//商品
                    final GoodObject goods = business.getTradeData().getOrderList().get(j);
                    View goodsLayout = getLayoutInflater().inflate(R.layout.item_order_adapter_business_good, null);
                    ImageView goodsImg = goodsLayout.findViewById(R.id.goods_img);
                    TextView goodsDiscribe = goodsLayout.findViewById(R.id.goods_describe);
                    TextView goodsFormat = goodsLayout.findViewById(R.id.goods_format);
                    TextView goodsCount = goodsLayout.findViewById(R.id.goods_count);
                    TextView goodsPrice = goodsLayout.findViewById(R.id.goods_price);
                    imageLoaderUtils.displayImage(goods.getPic_path(), goodsImg);
                    goodsFormat.setText(goods.getSpec_info());
                    goodsDiscribe.setText(goods.getTitle());
                    goodsCount.setText("x" + goods.getNum());
                    goodsPrice.setText("" + (int) ((float) goods.getPrice() * 100));
                    goodsLayout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            MallGoodsActivity.jump(OrderDetailsActivity.this, goods.getItem_id());
                        }
                    });
                    businessGoodsLayout.addView(goodsLayout);
                }
            }
        }
    }

    /**
     * 地址信息
     */
    private void initAddressData() {
        if (userAddress != null) {
            texUserName.setText(userAddress.getReceiverName());
            texUserPhone.setText(userAddress.getReceiverMobile());
            texUserAddress.setText(userAddress.getReceiversState() + userAddress.getReceiverCity() + userAddress.getReceiverDistrict() + userAddress.getReceiverAddress());
//            texOrderNo.setText(userAddress.getTid());
        }
    }

    private void setListener() {
        QQ.setOnClickListener(this);
        phone.setOnClickListener(this);
        btnCancle.setOnClickListener(this);
        btnPay.setOnClickListener(this);
        btnBack.setOnClickListener(this);
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_left_button:
                finish();
                break;
            case R.id.order_qq_img:
                CommonUtils.gotoQQ(context, Globals.LISHE_QQ);
                break;
            case R.id.order_phone_img:
                createCallPhone();
                break;
            case R.id.cancle_button:
//                cancleOrder();
                String orderStatus = order.getStatusToString();
                switch (orderStatus) {
                    case "待付款":
                        windowMsg = context.getString(R.string.iscancle_order);
                        cancleOrder(order, windowMsg, orderStatus);
                        break;
                    case "待发货":
                    case "买家已付款":
                        toast("已提醒店家发货！");
//                        confirmSendGoods();
                        break;
                    case "待收货":
                    case "卖家已发货":
                        windowMsg = context.getString(R.string.isreceive_order);
//                        cancleOrder(order, windowMsg, orderStatus);
                        //查看物流
                        LogisticsActivity.jump(OrderDetailsActivity.this, order.getPayment_id());
                        break;
                }
                break;
            case R.id.pay_button:
                Log.e("去支付", "");
                PayActivity.jump(OrderDetailsActivity.this, order);
                break;
        }
    }

    /**
     * 获取订单收货地址
     */
    class GetOrderAddress extends AsyncTask<String, String, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
        }

        @Override
        protected String doInBackground(String... strings) {
//            HttpMyOrder.getOrderAddress("010e1ca23f64fe23b9cb2b587b9fc36b", order.getOrderPaymentId() + "", responseHandler);
            HttpMyOrder.getOrderAddress(token, order.getTrade_paybillData().get(0).getTid() + "", responseHandler);
            return null;
        }
    }

    AsyncHttpResponseHandler responseHandler = new AsyncHttpResponseHandler() {
        @Override
        public void onSuccess(int i, Header[] headers, byte[] bytes) {
            String result = new String(bytes);
            Log.e("result", result);
            try {
                JSONObject jsonObject = new JSONObject(result);
                int erroCode = jsonObject.optInt("errcode");
                int resultcode = jsonObject.optInt("result");
                if (erroCode == 0 && resultcode == 100) {
                    JSONObject data = jsonObject.optJSONObject("data");
                    userAddress = new UserAddressObject();
                    userAddress.optJson(userAddress, data);
                    initAddressData();
                } else {
                    String msg = jsonObject.optString("msg");
                    toast(msg);
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {

        }
    };

    /**
     * 拨号
     */
    private void createCallPhone() {
        ConfirmDialog.Builder callPhoneDialog = new ConfirmDialog.Builder(context);
        callPhoneDialog.setContent(Globals.LISHE_PHONE);
        callPhoneDialog.setContentGravity(Gravity.CENTER_HORIZONTAL);
        callPhoneDialog.setPositiveButton("确定", new ConfirmDialog.Builder.OnPositiveListener() {
            @Override
            public void onPositive(ConfirmDialog dialog) {
                dialog.dismiss();
                CommonUtils.callPhone((Activity) context, Globals.LISHE_PHONE);
            }
        });
        callPhoneDialog.show();
    }

    /**
     * 取消订单
     */
    private void cancleOrder(final OrderObject orderObject, String content, final String orderStatus) {
        if (cancleOrderDialog == null) {
            cancleOrderDialog = new ConfirmDialog.Builder(context);
        }
        cancleOrderDialog.setContent(content);
        cancleOrderDialog.setContentGravity(Gravity.CENTER_HORIZONTAL);
        cancleOrderDialog.setPositiveButton("确定", new ConfirmDialog.Builder.OnPositiveListener() {
            @Override
            public void onPositive(ConfirmDialog dialog) {
                dialog.dismiss();
                switch (orderStatus) {
                    case "取消订单":
                    case "待付款":
                        LoadingUtils.createLoadingDialog(OrderDetailsActivity.this, "正在取消...", false);
                        HttpMyOrder.cancleOrder(token, orderObject.getPayment_id(), new AsyncHttpResponseHandler() {
                            @Override
                            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                                LoadingUtils.closeDialog();
                                String result = new String(bytes);
                                Log.e("取消订单", result);
                                JSONObject jsonObject = null;
                                try {
                                    jsonObject = new JSONObject(result);
                                    if (jsonObject.optInt("errcode") == 0 && jsonObject.optInt("result") == 100) {
                                        finish();
                                    }
                                    String msg = jsonObject.optString("msg");
                                    toast(msg);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                                toast(context.getString(R.string.network_or_server_exception));
                                LoadingUtils.closeDialog();
                            }
                        });
                        break;
                    case "确认收货":
                        HttpMyOrder.confirmOrder(token, orderObject.getPayment_id(), new AsyncHttpResponseHandler() {
                            @Override
                            public void onSuccess(int i, Header[] headers, byte[] bytes) {
                                String result = new String(bytes);
                                JSONObject jsonObject = null;
                                try {
                                    jsonObject = new JSONObject(result);
                                    String msg = jsonObject.optString("msg");
                                    toast(msg);
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onFailure(int i, Header[] headers, byte[] bytes, Throwable throwable) {
                                toast(context.getString(R.string.network_or_server_exception));
                            }
                        });
                        break;
                    case "立即付款":

                        break;
                }
            }
        });
        cancleOrderDialog.show();
    }

}
